import React, {useEffect, useState} from 'react';
import {atom, useRecoilValueLoadable} from "recoil";

const asyncData = atom({
    key: 'asyncData',
    default: (async function (){
        return await getData();
    })()
})

function getData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve([{
                a: "a",
                b: "b"
            }])
        }, 3000)
    })

}

function ComponentALoadableState() {
    console.log('--useRecoilStateLoadable in recoil--')

    const userNameLoadable = useRecoilValueLoadable(asyncData);
    const loading = () => (<div className="form-group border">Loading...</div>);
    switch (userNameLoadable.state) {
        case 'hasValue':
            return <div className="form-group border">
                <h3>useRecoilValueLoadable</h3>
                <ul>{userNameLoadable.contents.map(item => {
                    return <li key={+new Date()}>{item.a + '--' + item.b}</li>
                })}</ul>
            </div>;
        case 'loading':
            return loading();
        case 'hasError':
            throw userNameLoadable.contents;
        default:
            return loading();
    }
}

export default React.memo(ComponentALoadableState);